package com.zwr.sheller.customer.controller;

import com.zwr.sheller.core.common.JsonResult;
import com.zwr.sheller.core.common.KQRBusinessException;
import com.zwr.sheller.core.common.KQRExceptionCode;
import com.zwr.sheller.core.pojo.Goods;
import com.zwr.sheller.core.pojo.User;
import com.zwr.sheller.core.util.RegexUtil;
import com.zwr.sheller.customer.Service.ConcernsService;
import com.zwr.sheller.customer.Service.SendCodeSmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 *@author Kang
 *@date
 */
@RestController
@RequestMapping("/partPersonalCenterController")
@Api(value = "部分个人中心接口")
public class PartPersonalCenterController {

    //用户id从线程中获取
    private final Long id=1L;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    ConcernsService concernsService;

    @ApiOperation(value = "我的优惠券")
    @PostMapping("/myCoupons")
    public Map<String,Object> myCoupons(){

        List<Map<String, Object> > map = concernsService.selectByCoupons(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("data",map);
        return jsonResult.getMap();
    }


    @ApiOperation(value = "领取优惠券")
    @PostMapping("/receiveCoupons")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponsId" ,dataType = "Long",required = true,paramType = "query" ,value = "优惠券id")
    })
    public Map<String,Object> receiveCoupons(Long couponsId){
        concernsService.receiveCoupons(id,couponsId);

        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation(value = "我的收藏")
    @PostMapping("/myFavorites")
    public Map<String,Object> myFavorites(){

        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation(value = "我的关注")
    @PostMapping("/browsingHistory")
    public Map<String,Object> browsingHistory(){

        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }


    private String USER_CONCERNS="user_concerns:";

    private  String SALES_VOLUME_SHOPPING="salesVolume_shopping:";

    @ApiOperation(value = "添加浏览记录")
    @PostMapping("/addMyConcerns")
    public Map<String,Object> addMyConcerns(Long shoppingId){

        Goods goods = concernsService.findGoods(shoppingId);

        //获取用户浏览过的商户id
        List<Object> range = redisTemplate.opsForList().range(USER_CONCERNS + id, 0, -1);
       if (range!=null){
           for (int i = 0; i < range.size(); i++) {
               //查询商品以前是否浏览过，若是浏览过则删除
               if (Long.valueOf(range.get(i).toString()).equals(shoppingId)==true){
                   if (i==0){
                       redisTemplate.opsForList().rightPop(USER_CONCERNS+id);
                   }else {
                       redisTemplate.opsForList().trim(USER_CONCERNS+id,i,i+2);
                       System.out.println(i);
                       //删除之前的商品缓存后续导入新的重载缓存时间
                       redisTemplate.delete(SALES_VOLUME_SHOPPING+shoppingId);
                   }

               }
           }
       }
        //添加浏览的商品id
        redisTemplate.opsForList().rightPush(USER_CONCERNS+id,shoppingId);
        //添加浏览记录，设置过期时间
        redisTemplate.opsForValue().set(SALES_VOLUME_SHOPPING+shoppingId,goods.getGoodsName()+goods.getGoodsTitle()+goods.getGoodsKeyWord(),30,TimeUnit.DAYS);
        System.out.println(goods.getGoodsName()+"------------------------------------------------");
        System.out.println(goods);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation(value = "浏览记录")
    @PostMapping("/myConcerns")
    public Map<String,Object> myConcerns(){
        //获取用户浏览过的商户id
        List<Object> range = redisTemplate.opsForList().range(USER_CONCERNS + id, 0, -1);
        ArrayList list=new ArrayList();

        if (range!=null){
            for (Object o : range) {
                Object o1 = redisTemplate.opsForValue().get(SALES_VOLUME_SHOPPING + o);
                list.add(o1);
            }
        }

        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("data",list);
        return jsonResult.getMap();
    }


    @ApiOperation(value = "编辑基本信息")
    @PostMapping("/updateInformation")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", dataType = "String", required = true, paramType = "query", value = "收货人姓名"),
            @ApiImplicitParam(name = "userPhone", dataType = "String", required = true, paramType = "query", value = "收货人手机号"),
            @ApiImplicitParam(name = "userRetailName", dataType = "String", required = true, paramType = "query", value = "收货地址（省、市）"),
            @ApiImplicitParam(name = "userPrinciple", dataType = "String", required = true, paramType = "query", value = "详细地址"),
            @ApiImplicitParam(name = "userHead", dataType = "String", required = true, paramType = "query", value = "头像地址")
    })
    public Map<String,Object> updateInformation(String userPhone,String userName,String userRetailName,String userPrinciple,String userHead) throws KQRBusinessException {

        if (RegexUtil.isPhoneNumber(userPhone)){
            throw new KQRBusinessException(KQRExceptionCode.UNKNOWN_EXCEPTION);
        }
        concernsService.updateInformation(id,userPhone,userName,userRetailName,userPrinciple,userHead);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation(value = "基本信息展示")
    @PostMapping("/selectInformation")
    public Map<String,Object> selectInformation(){
        User user = concernsService.selectInformation(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("data",user);
        return jsonResult.getMap();
    }

    /**-------------------------------------------------------------------------------------------------
     *
     *--------------------------------------------------------------------------------------------------
     */



    public static  final String CODE_SMS="code_sms:";

    @Autowired(required = false)
    SendCodeSmsService sendCodeSmsService;

    @PostMapping("/send")
    @ApiOperation("发送验证码接口")
    public Map<String, Object> sendSMS(String phone) {
        String s = sendCodeSmsService.sendLoginSms(phone);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("发送成功");
        jsonResult.setField("code", s);
        return jsonResult.getMap();
    }

    @ApiOperation(value = "修改绑定手机号")
    @PostMapping("/updatePhone")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userPhone", dataType = "String", required = true, paramType = "query", value = "手机号"),
            @ApiImplicitParam(name = "code", dataType = "String", required = true, paramType = "query", value = "验证码"),
            @ApiImplicitParam(name = "userNewPhone", dataType = "String", required = true, paramType = "query", value = "新手机号")
    })
    public Map<String,Object> updatePhone(String phone,String code,String userNewPhone) throws KQRBusinessException {
        User user = concernsService.selectInformation(id);
        String userPhone = user.getUserPhone();
        if (phone.equals(userPhone)!=true) {
            throw new KQRBusinessException(KQRExceptionCode.NOT_PHONE_MORE);
        }
        Object o = redisTemplate.opsForValue().get(CODE_SMS + phone);
        if (o.toString().equals(code)!=true){
            throw new KQRBusinessException(KQRExceptionCode.NOT_CODE_HOUSE);
        }
        redisTemplate.delete(CODE_SMS+phone);
        concernsService.updatePhone(id,userNewPhone);

        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("/updatePassword")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userPhone", dataType = "String", required = true, paramType = "query", value = "手机号"),
            @ApiImplicitParam(name = "code", dataType = "String", required = true, paramType = "query", value = "验证码"),
            @ApiImplicitParam(name = "userNewpwd", dataType = "String", required = true, paramType = "query", value = "新密码"),
            @ApiImplicitParam(name = "userNewPassword", dataType = "String", required = true, paramType = "query", value = "再次输入密码")
    })
    public Map<String,Object> updatePassword(String phone,String code,String userNewpwd,String userNewPassword) throws KQRBusinessException {
        User user = concernsService.selectInformation(id);
        String userPhone = user.getUserPhone();
        if (phone.equals(userPhone)!=true) {
            throw new KQRBusinessException(KQRExceptionCode.NOT_PHONE_MORE);
        }
        Object o = redisTemplate.opsForValue().get(CODE_SMS + phone);
        if (o.toString().equals(code)!=true){
            throw new KQRBusinessException(KQRExceptionCode.NOT_CODE_HOUSE);
        }
        redisTemplate.delete(CODE_SMS+phone);
        if (userNewPassword.equals(userNewpwd)!=true){
            throw new KQRBusinessException(KQRExceptionCode.NOT_USER_PWD);
        }
        concernsService.updatePassword(id,userNewpwd);


        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }
}
